﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ess_zbfz_main.entity;
using ParsePtb;
using ParsePtb.Comm;
using ParsePtb.consts;
using ParsePtb.entity;
using ParsePtb.sign;
using ParsePtb.util;

namespace ParseTask
{
    public partial class ParseForm : Form
    {
        //初始化时解析的数量
        private int initParseCount = 0;

        //初始化时解析结束成功的数量
        private int parseSuccessCount = 0;

        // 初始化时解析结束的失败数
        private int parseFailCount = 0;

        private static string title = "文件解析";

        private static bool IS_PARSING = false;

        //当前操作表
        private string tableName;

        /// <summary>
        /// 本地数据库
        /// </summary>
        private static string sqliteDirect = ConfigurationManager.AppSettings.Get("dbRootFolder");
        /// <summary>
        /// 本地数据库
        /// </summary>
        private static string sqliteDbName = ConfigurationManager.AppSettings.Get("dbName");

        //获取表配置信息  (动态常量)
        public Dictionary<string, MySign> fiterTables = GetTableConfig();


        // 文件存放根目录
        private string saveFileRootPath = AppDomain.CurrentDomain.BaseDirectory + "parse";

        //db文件的记录 防止重复
        private Dictionary<string, FileInfo> listDict = new Dictionary<string, FileInfo>();

        private string zipPassWord = ConfigurationManager.AppSettings.Get("zipPassWord");

        //zip根目录  db文件的根目录
        private string sqliteRoot;

        //sqlite的名称加后缀
        private string sqliteName = null;

        //所有的check文件 字典
        private Dictionary<string, FileInfo> confirmDict = new Dictionary<string, FileInfo>();

        //解密
        private MainSm4 mainSm4 = new MainSm4();


        public const int WM_DEVICECHANGE = 0x219;
        public const int DBT_DEVICEARRIVAL = 0x8000;    //如果m.Msg的值为0x8000那么表示有U盘插入
        public const int DBT_CONFIGCHANGECANCELED = 0x0019;
        public const int DBT_CONFIGCHANGED = 0x0018;
        public const int DBT_CUSTOMEVENT = 0x8006;
        public const int DBT_DEVICEQUERYREMOVE = 0x8001;
        public const int DBT_DEVICEQUERYREMOVEFAILED = 0x8002;
        public const int DBT_DEVICEREMOVECOMPLETE = 0X8004;
        public const int DBT_DEVICEREMOVEPENDING = 0x8003;
        public const int DBT_DEVICETYPESPECIFIC = 0x8005;
        public const int DBT_DEVNODES_CHANGED = 0x0007;
        public const int DBT_QUERYCHANGECONFIG = 0x0017;
        public const int DBT_USERDEFINED = 0xFFFF;
        public Message mm;


        /// <summary>
        /// 监视Windows消息
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            try
            {
                if (m.Msg == WM_DEVICECHANGE)
                {
                    switch (m.WParam.ToInt32())
                    {
                        case WM_DEVICECHANGE:
                            break;
                        case DBT_DEVICEARRIVAL:         //U盘插入
                            //GetDBList();
                            //Console.WriteLine("");
                            //listBox1.Items.Add("U盘已插入,盘符为:" + strDrivers[strDrivers.Count() - 1]);
                            break;
                        case DBT_CONFIGCHANGECANCELED:
                            break;
                        case DBT_CONFIGCHANGED:
                            break;
                        case DBT_CUSTOMEVENT:
                            break;
                        case DBT_DEVICEQUERYREMOVE:
                            Console.WriteLine("DBT_DEVICEQUERYREMOVE");
                            break;
                        case DBT_DEVICEQUERYREMOVEFAILED:
                            Console.WriteLine("DBT_DEVICEQUERYREMOVEFAILED");
                            break;
                        case DBT_DEVICEREMOVECOMPLETE:   //U盘卸载 ==>移除时间
                            Console.WriteLine("DBT_DEVICEREMOVECOMPLETE");
                            break;
                        case DBT_DEVICEREMOVEPENDING:
                            Console.WriteLine("DBT_DEVICEREMOVEPENDING");
                            break;
                        case DBT_DEVNODES_CHANGED:
                            Console.WriteLine("DBT_DEVNODES_CHANGED");
                            break;
                        case DBT_QUERYCHANGECONFIG:
                            break;
                        case DBT_USERDEFINED:
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            base.WndProc(ref m); //将系统消息传递自父类的WndProc
        }

        /// <summary>
        /// 获取db文件的列表
        /// </summary>
        private void GetDBList()
        {
            if (string.IsNullOrEmpty(this.DbPathText.Text))
            {
                MessageBox.Show("未指定DB文件解析的路径,请先指定路径");
                return;
            }
            //string[] strDrivers = Environment.GetLogicalDrives();

            //一般磁盘会有2个盘符
            DirectoryInfo directoryInfo;
            FileInfo[] fileInfos;

            directoryInfo = new DirectoryInfo(this.DbPathText.Text);
            fileInfos = directoryInfo.GetFiles();

            foreach (var item in fileInfos)
            {
                //".sqlite".Equals(item.Extension) || ".DB".Equals(item.Extension) || ".db".Equals(item.Extension)
                if (item.FullName.ToLower().EndsWith("_enc.zip"))
                {
                    if (listDict.ContainsKey(item.FullName))
                    {
                        continue;
                    }

                    //dbFileList.Add(item);
                    listViewFiles.Items.Add(new ListViewItem() { Text = item.FullName });
                    listDict.Add(item.FullName, item);
                    //记录当前解析的文件数量
                    this.initParseCount++;
                }
            }

        }

        public ParseForm()
        {
            InitializeComponent();
        }

        private void ParseForm_Load(object sender, EventArgs e)
        {
            this.rootPathText.Text = saveFileRootPath;
            CheckForIllegalCrossThreadCalls = false;

            listViewFiles.Items.Clear();//清空记录
            listViewFiles.View = View.Details;
            listViewFiles.EndUpdate();

            //单纯增加行直接的间距
            ImageList imageList1 = new ImageList();
            imageList1.ImageSize = new System.Drawing.Size(2, 20);
            imageList1.TransparentColor = System.Drawing.Color.Transparent;
            listViewFiles.SmallImageList = imageList1;

            this.columnHeader1.TextAlign = HorizontalAlignment.Center;
            this.columnHeader2.TextAlign = HorizontalAlignment.Center;
            this.columnHeader3.TextAlign = HorizontalAlignment.Center;

            this.listViewLogs.GridLines = true;
            title = "文件解析";
            this.mainTitle.Text = title;

            //Form owner = this.Owner;
        }



        /// <summary>
        /// 解析db(sqlite)文件
        /// </summary>
        public void ParseDB()
        {
            ListViewItem curViewItem = null;
            DirectoryInfo directoryInfo;
            string confirmPrefix;
            try
            {
                ListView.ListViewItemCollection dbFileList = listViewFiles.Items;
                if (dbFileList == null || dbFileList.Count <= 0)
                {
                    this.lblunanalysedQty.Text = "0";
                    return;
                }

                this.lblunanalysedQty.Text = Convert.ToString(initParseCount);
                this.lblunanalysedQty.Update();


                //存在文件正在解析
                if (IS_PARSING)
                {
                    return;
                }

                IS_PARSING = true;


                //查询当前数据库的所有表
                string allTableSql = "select name,tbl_name FROM sqlite_master where type='table'";

                OsZbSupplierInfo currentosZbSupplier = null;
                OsZbPurchaseProjectInfo currentProject = null;
                StringBuilder tableSelects;


                //查询的表  需要防止数据表和数据不对  放在变量文件里面
                Dictionary<string, string> selectTables;
                string supplierSql;
                string projectSql;

                ListView.ListViewItemCollection itemList = listViewFiles.Items;
                List<OsZbSupplierInfo> osZbSupplierList;
                List<DBTable> lists;

                string sqliteRoot;
                string sqliteName = null;

                DirectoryInfo directory;
                FileInfo[] fileInfos;

                //加解密流
                FileStream encFs = null;
                BinaryReader encBinary = null;
                byte[] btyeArr = null;
                byte[] encByte = null;
                FileStream decStream = null;
                BinaryWriter decWriter = null;

                foreach (var item in dbFileList)
                {
                    selectTables = new Dictionary<string, string>();
                    curViewItem = (ListViewItem)item;
                    AppendListViewItemToLogs(curViewItem.Text, "开始解析");

                    //相当于解压根目录
                    sqliteRoot = Path.Combine(listDict[curViewItem.Text].DirectoryName,
                    listDict[curViewItem.Text].Name.Replace(listDict[curViewItem.Text].Extension, ""));//sqlite

                    directoryInfo = new DirectoryInfo(sqliteRoot);

                    //解压文件夹存在 先删除
                    /*if (directoryInfo.Exists)
                    {
                        directoryInfo.Delete(true);
                    }*/

                    //解压操作
                    ZipHelper.DeCompressionFile(curViewItem.Text, sqliteRoot, zipPassWord);

                    directory = new DirectoryInfo(sqliteRoot);
                    fileInfos = directory.GetFiles();

                    //文件信息
                    foreach (var fi in fileInfos)
                    {
                        if (".sqlite".Equals(fi.Extension.ToLower()))
                        {
                            sqliteName = fi.Name;
                        }
                    }

                    //zip同级
                    fileInfos = listDict[curViewItem.Text].Directory.GetFiles();
                    foreach (var fi in fileInfos)
                    {
                        if (fi.Name.ToLower().Contains("confirm.enc") && !confirmDict.ContainsKey(fi.Name))
                        {
                            confirmDict.Add(fi.Name, fi);
                        }
                    }

                    if (string.IsNullOrEmpty(sqliteName))
                    {
                        LogsHelper.addLog($"{curViewItem.Text}压缩文件中db文件找不到");
                        continue;
                    }


                    tableSelects = new StringBuilder();

                    lists = SQLiteLibrary.SelectBySql<DBTable>(sqliteRoot, sqliteName, allTableSql);

                    //先查当前供应商信息
                    supplierSql = "SELECT OS_ZB_SUPPLIER_INFO.* FROM OS_ZB_SUPPLIER_INFO  ORDER BY UPDATE_TIME DESC limit 0,1";

                    osZbSupplierList = SQLiteLibrary.SelectBySql<OsZbSupplierInfo>(sqliteRoot, sqliteName, supplierSql);

                    currentosZbSupplier = osZbSupplierList != null ? osZbSupplierList[0] : new OsZbSupplierInfo();

                    //在查当前项目信息
                    projectSql = "SELECT OS_ZB_PURCHASE_PROJECT_INFO.*,group_concat(''''||mark_no||'''') marks FROM OS_ZB_PURCHASE_PROJECT_INFO ";
                    List<OsZbPurchaseProjectInfo> projectInfoList = SQLiteLibrary.SelectBySql<OsZbPurchaseProjectInfo>(sqliteRoot, sqliteName, projectSql);
                    currentProject = projectInfoList != null ? projectInfoList[0] : new OsZbPurchaseProjectInfo();

                    //解密confirm文件
                    confirmPrefix = $"{currentProject.ProjectNo}_{currentosZbSupplier.EntName}";//文件前缀
                    if (confirmDict.ContainsKey($"{confirmPrefix}_confirm.enc"))
                    {
                        DecConfirmFile(currentosZbSupplier, encFs, encBinary, btyeArr, encByte, decStream, decWriter, $"{confirmPrefix}");
                    }

                    DataSet dataSet;
                    if (lists != null)
                    {
                        foreach (var dbItem in lists)
                        {
                            if (fiterTables.ContainsKey(dbItem.Name))
                            {
                                //该表忽略
                                if (fiterTables[dbItem.Name].Igore)
                                {
                                    Console.WriteLine($"-----------表 {dbItem.Name} 被过滤---------------");
                                    continue;
                                }
                                else
                                {
                                    if (!selectTables.ContainsKey(dbItem.Name))
                                    {
                                        selectTables.Add(dbItem.Name, dbItem.Name);
                                    }
                                    tableSelects.Append($"select * from {dbItem.Name} where 1=1 ");
                                    tableSelects.Append(fiterTables[dbItem.Name].HaveSupplier ?
                                        $" AND SUPPLIER_ID ='{currentosZbSupplier.Id}'" : "");

                                    //新增查询条件
                                    if (!string.IsNullOrEmpty(fiterTables[dbItem.Name].WhereCon))
                                    {
                                        tableSelects.Append(fiterTables[dbItem.Name].WhereCon
                                            .Replace("{PROJECT_NO}", currentProject.ProjectNo)
                                            .Replace("{SUPPLIER_ID}", currentosZbSupplier.Id)
                                            .Replace("{MARK_NO}", currentProject.Marks));
                                    }

                                    tableSelects.Append($";");
                                }
                                continue;
                            }
                        }

                        dataSet = SQLiteLibrary.QuerySet(sqliteRoot, sqliteName,
                            tableSelects.ToString(), selectTables);

                        //数据解析到oracle数据库
                        WriteToOracleDB(dataSet, fiterTables, currentosZbSupplier, currentProject);

                        //没有问题
                        AppendListViewItemToLogs(curViewItem.Text, "解析成功");
                        RemoveListViewItem(curViewItem.Text);

                        //解析成功个数
                        parseSuccessCount++;
                        this.parseSuccess.Text = $"解析成功数:{parseSuccessCount}";
                        this.parseSuccess.Update();

                        //待解析的个数
                        initParseCount = initParseCount - 1 < 0 ? initParseCount : initParseCount - 1;
                        this.lblunanalysedQty.Text = $"{initParseCount}";
                        this.lblunanalysedQty.Update();

                        //写入数据库
                        WriteToDBLog(curViewItem.Text, ResultEnum.Success, "解析成功");
                    }
                }
                IS_PARSING = false;
                //StopParse("解析结束");
            }
            catch (Exception ex)
            {
                LogsHelper.addLog("解析异常:" + ex.Message);
                IS_PARSING = false;
                if (curViewItem != null)
                {
                    AppendListViewItemToLogs(curViewItem.Text, "解析失败");
                    RemoveListViewItem(curViewItem.Text);

                    //写入数据库
                    WriteToDBLog(curViewItem.Text, ResultEnum.Fail, ex.Message);
                }

                //解析失败个数
                this.parseFailCount++;
                this.parseFail.Text = $"解析失败数:{parseFailCount}";
                this.parseFail.Update();

                //待解析的个数
                initParseCount = initParseCount - 1 < 0 ? initParseCount : initParseCount - 1;
                this.lblunanalysedQty.Text = $"{initParseCount}";
                this.lblunanalysedQty.Update();

                if (IS_PARSING)
                {
                    LogsHelper.AddErrorLog(ex.Message);//错误日志
                }
            }
            finally
            {
                /*// 不存在解析数据直接结束
                if (listViewFiles.Items.Count <= 0)
                {
                    StopParse("解析结束");
                }*/
            }

        }

        /// <summary>
        /// 解析结果写入数据库
        /// </summary>
        /// <param name="fullName"></param>
        /// <param name="success"></param>
        /// <param name="parseMsg"></param>
        private void WriteToDBLog(string fullName, ResultEnum success, string parseMsg)
        {
            try
            {
                string fileName = Path.GetFileName(fullName);
                string checkSql = $"SELECT * FROM SYS_UPLOAD_FILE_LOG WHERE FILE_NAME='{fileName}'";

                DataTable dataTable = SQLiteLibrary.selectDataBySql(sqliteDirect, sqliteDbName, checkSql);
                string handSql;
                string parseStatus = success == ResultEnum.Success ? "success" : "fail";
                parseMsg = success == ResultEnum.Success ? $"{parseMsg}" : $"当前操作表:{tableName},异常信息:{parseMsg}";
                if (dataTable.Rows.Count > 0)
                {
                    handSql = $"update SYS_UPLOAD_FILE_LOG set PARSE='1', PARSE_TIME = datetime('now', 'localtime'),PARSE_MSG='{parseMsg}',PARSE_STATUS='{parseStatus}' where FILE_NAME='{fileName}'";
                }
                else
                {
                    handSql = $"insert into SYS_UPLOAD_FILE_LOG(FULL_NAME,FILE_NAME,STATUS,PARSE,CREATE_TIME,PARSE_TIME,PARSE_MSG,PARSE_STATUS)";
                    handSql += $"values('{fullName}','{fileName}','直接解析','1',datetime('now', 'localtime'),datetime('now', 'localtime'),'{parseMsg}','{parseStatus}')";
                }

                SQLiteLibrary.insertData(sqliteDirect, sqliteDbName, handSql);
            }
            catch (Exception ex)
            {
                LogsHelper.AddErrorLog($"日志信息写入数据库异常:{ex.Message}");
            }
        }



        /// <summary>
        /// 解密confirm文件
        /// </summary>
        /// <param name="currentosZbSupplier"></param>
        /// <param name="encFs"></param>
        /// <param name="encBinary"></param>
        /// <param name="btyeArr"></param>
        /// <param name="encByte"></param>
        /// <param name="decStream"></param>
        /// <param name="decWriter"></param>
        private void DecConfirmFile(OsZbSupplierInfo currentosZbSupplier, FileStream encFs, BinaryReader encBinary, byte[] btyeArr, byte[] encByte, FileStream decStream, BinaryWriter decWriter, string confirmPrefix)
        {
            try
            {
                string confirmRoot = confirmDict[$"{confirmPrefix}_confirm.enc"].DirectoryName;
                encFs = new FileStream(confirmDict[$"{confirmPrefix}_confirm.enc"].FullName, FileMode.Open);
                encBinary = new BinaryReader(encFs);
                btyeArr = encBinary.ReadBytes((int)encFs.Length);
                encByte = new MainSm4().Decrypt_ECB(Sm4.SM4_KEY, false, btyeArr);
                decStream = new FileStream(Path.Combine(confirmRoot, $"{confirmPrefix}_confirm.txt"), FileMode.Create);
                decWriter = new BinaryWriter(decStream);
                decWriter.Write(encByte);
                WriteToDBLog($"{confirmPrefix}_confirm.enc", ResultEnum.Success, "解析成功");
            }
            catch (Exception ex)
            {
                LogsHelper.AddErrorLog("confirm解析失败:" + ex.Message);
                LogsHelper.addLog("confirm解析失败:" + ex.Message);
                WriteToDBLog($"{confirmPrefix}_confirm.enc", ResultEnum.Fail, ex.Message);
            }
            finally
            {
                if (decStream != null)
                {
                    decStream.Close();
                }
                if (decWriter != null)
                {
                    decWriter.Close();
                }
                if (encFs != null)
                {
                    encFs.Close();
                }
                if (encBinary != null)
                {
                    encBinary.Close();
                }

            }

        }

        /// <summary>
        /// 停止解析
        /// </summary>
        private void StopParse(string msg)
        {

            this.TimerParse.Stop();
            this.buttonStart.ForeColor = System.Drawing.Color.Black;
            this.buttonStart.Text = "启动解析";
            this.buttonStart.Click += ButtonStart_Click;
            this.buttonStart.Click -= ButtonStop_Click;

            this.lblTimerMsg.Text = msg;
            this.lblTimerMsg.ForeColor = System.Drawing.Color.Red;
            //this.rootPathSelect.Enabled = false;
            this.DbPathSelect.Enabled = true;
            this.FilePathSelect.Enabled = true;
        }

        /// <summary>
        ///  获取表配置信息
        /// </summary>
        /// <param name="fiterTables"></param>
        /// <returns></returns>
        private static Dictionary<string, MySign> GetTableConfig()
        {
            Dictionary<string, MySign> fiterTables = new Dictionary<string, MySign>();

            //基础表
            fiterTables.Add("OS_ZB_SUPPLIER_ASERVICE_INFO", new MySign() { }.Filter("IS_RELATION"));//配送方案
            fiterTables.Add("OS_ZB_SUPPLIER_CAPACITY_INFO", new MySign() { }.Filter("IS_RELATION"));//产品产能
            fiterTables.Add("OS_ZB_SUPPLIER_CERT_INFO", new MySign() { }.Filter("IS_RELATION"));//资质证书
            fiterTables.Add("OS_ZB_SUPPLIER_CREDIT_INFO", new MySign() { }.Filter("IS_RELATION,FILE_DISP_NAME,FILE_PATH,FILE_FORMAT"));
            fiterTables.Add("OS_ZB_SUPPLIER_EQUITY_INFO", new MySign() { }.Filter("IS_RELATION"));//股权结构
            fiterTables.Add("OS_ZB_SUPPLIER_FINANCE_INFO", new MySign() { }.Filter("IS_RELATION,TYPE"));//财务数据
            fiterTables.Add("OS_ZB_SUPPLIER_LABEQP_INFO", new MySign() { }.Filter("IS_RELATION"));//实验设备
            fiterTables.Add("OS_ZB_SUPPLIER_MEQP_INFO", new MySign() { }.Filter("IS_RELATION"));//制造设备
            fiterTables.Add("OS_ZB_SUPPLIER_PROCESS_INFO", new MySign() { }.Filter("IS_RELATION"));//制造工艺
            fiterTables.Add("OS_ZB_SUPPLIER_PRODUCT_INFO", new MySign() { }.Filter("IS_RELATION").Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_QUALIFY_INFO", new MySign() { }.Filter("IS_RELATION,PROJECT_ID"));//资质业绩
            fiterTables.Add("OS_ZB_SUPPLIER_REPORT_INFO", new MySign() { }.Filter("IS_RELATION"));//实验报告
            fiterTables.Add("OS_ZB_SUPPLIER_BRAND_AGENT", new MySign() { });
            fiterTables.Add("OS_ZB_SUPPLIER_SALES_INFO", new MySign() { }.Filter("IS_RELATION"));//销售业绩
            //产品部件信息
            fiterTables.Add("OS_ZB_SUPPLIER_PARTS_INFO", new MySign() { }.Colums(Constant.PARTS_COLUMNS).Where(Constant.DefaultCon));
            //其实这个算商务和技术支持文件选填的表

            //引用表
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_CAPACITY_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_CAPACITY_RELATE").Colums(Constant.RELAT_COMM_COLUMNS + ",PRODUCT_TYPE").Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_CERT_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_CERT_INFO_RELAT").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_CREDIT_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_CREDIT_RELATE").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_FINANCE_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_FINANCE_RELATE").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_LABEQP_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_LABEQP_RELATE").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_MEQP_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_MEQP_RELATE").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_REPORT_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_REPORT_RELATE").Colums(Constant.RELAT_COMM_COLUMNS).Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_SALES_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_SALES_RELATE").Colums(Constant.RELAT_COMM_COLUMNS + ",PRODUCT_TYPE").Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_ASERVICE_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_ASERVICE_RELATE").Colums(Constant.RELAT_COMM_COLUMNS + ", QUALITY_ASSURE_YEAR,ENT_COMMIT").Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_EQUITY_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_EQUITY_RELATE").Colums(Constant.RELAT_COMM_COLUMNS + ",GQJGSM,EQUITY_NAME,POSITION,ID_CARD,SHARES,SHARES_TYPE,PEOPEL_TYPE").Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_BIAO_ZIXIN_INFO", new MySign() { }.Alias("OS_ZB_SUPPLIER_ZIXIN_RELATE").Colums(Constant.RELAT_COMM_COLUMNS + ",ZXZMCJYH,ZXDJ,YEAR_SJ").Where(Constant.DefaultCon));

            //其他 -- 保证金 和响应情况表 标书文件
            fiterTables.Add("OS_ZB_SUPPLIER_RESPONSE_INFO", new MySign() { }.Where(Constant.DefaultCon));
            fiterTables.Add("OS_ZB_SUPPLIER_DEPOSIT", new MySign() { }.Where(Constant.DefaultCon));

            //线上线下数据库很大不一致 重新定义
            //fiterTables.Add("OS_ZB_SUPPLIER_BID_ATTACHMENT", new MySign() { }.Colums(Constant.BID_ATTACH_COLUMNS));
            fiterTables.Add("OS_ZB_SUPPLIER_DEPOSIT_DETAIL", new MySign() { }.AppendFormat("PAY_TIME", Constant.FORMAT_DATE_TIMESTAMP));//HaveSupplier = false 
            fiterTables.Add("OS_ZB_SUPPLIER_INFO", new MySign() { HaveSupplier = false }.Colums(Constant.SUPPLIER_INFO_COLUMNS).Where(" AND ID ='{SUPPLIER_ID}'"));
            fiterTables.Add("OS_ZB_MATERIAL_LIST", new MySign() { HaveSupplier = false }); //货物清单

            //忽略的表
            fiterTables.Add("CM_C_DICTIONARY_DETAILS", new MySign() { Igore = true });//忽略
            fiterTables.Add("OS_ZB_SUPPLIER_ZIXIN_INFO", new MySign() { Igore = true });//这张表实际没用上 【忽略】


            //走自定义的方法的 “表”
            fiterTables.Add("SYS_FILE_INFO", new MySign() { DefinedHander = true, HaveSupplier = false });//文件信息
            fiterTables.Add("OS_ZB_PURCHASE_PROJECT_INFO", new MySign() { DefinedHander = true });//项目表 
            fiterTables.Add("OS_ZB_SUPPLIER_BID_ATTACHMENT", new MySign() { DefinedHander = true }.Where(Constant.DefaultCon));//标书文件


            //先从数据库获取 == 覆盖默认配置(防止程序解析失败 还得改代码)
            try
            {
                if (!string.IsNullOrEmpty(sqliteDbName))
                {
                    string sql = "select * from SYS_TABLE_CONFIG_INFO group by Table_Name";
                    DataTable dataTable = SQLiteLibrary.selectBySql(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, sqliteDirect), sqliteDbName, sql);
                    DataRowCollection dataRowList = dataTable.Rows;
                    DataRow dataRow;
                    MySign mySign;
                    for (int i = 0; i < dataRowList.Count; i++)
                    {
                        dataRow = dataRowList[i];
                        mySign = new MySign();
                        if (string.IsNullOrEmpty(dataRow.Field<string>("Table_Name")))
                        {
                            break;
                        }
                        if (fiterTables.ContainsKey(dataRow.Field<string>("Table_Name")))
                        {
                            mySign = fiterTables[dataRow.Field<string>("Table_Name")];
                            fiterTables.Remove(dataRow.Field<string>("Table_Name"));
                        }

                        mySign.Igore = !string.IsNullOrEmpty(dataRow.Field<string>("Igore")) && !"0".Equals(dataRow.Field<string>("Igore"));
                        mySign.DefinedHander = !string.IsNullOrEmpty(dataRow.Field<string>("DefinedHander")) && !"0".Equals(dataRow.Field<string>("DefinedHander"));
                        mySign.HaveSupplier = !string.IsNullOrEmpty(dataRow.Field<string>("HaveSupplier")) && !"0".Equals(dataRow.Field<string>("HaveSupplier"));
                        mySign.Alias(dataRow.Field<string>("TableAlias"));
                        mySign.Colums(dataRow.Field<string>("Fields"));
                        mySign.Filter(dataRow.Field<string>("IgoreFields"));
                        fiterTables.Add(dataRow.Field<string>("Table_Name"), mySign);
                    }

                }

            }
            catch (Exception ex)
            {
                LogsHelper.AddErrorLog("查询数据库{SYS_TABLE_CONFIG_INFO}配置出错:" + ex.Message);
            }

            return fiterTables;
        }

        /// <summary>
        /// 数据解析到oracle数据库
        /// </summary>
        /// <param name="dataSet"></param>
        private void WriteToOracleDB(DataSet dataSet, Dictionary<string, MySign> fiterTables, OsZbSupplierInfo currentosZbSupplier, OsZbPurchaseProjectInfo currentProject)
        {
            //针对单个DB文件的错误
            int doCount = 0;

            DataTableCollection tables = dataSet.Tables;
            StringBuilder sqlHeadSbf;
            object currentValue;
            StringBuilder contentSbf;
            MySign mySign = null;

            DataColumnCollection dataColumns;
            DataRowCollection rows;

            StringBuilder allColums;
            string deleteTableSql;
            object[] values;
            Dictionary<string, string> columsDict;


            for (int i = 0; i < tables.Count; i++)
            {
                dataColumns = tables[i].Columns;
                rows = tables[i].Rows;
                tableName = tables[i].TableName;
                columsDict = new Dictionary<string, string>();
                allColums = new StringBuilder();//记录所有列


                if (fiterTables.ContainsKey(tables[i].TableName))
                {
                    mySign = fiterTables[tables[i].TableName];
                    tableName = mySign.TableAlias == null ? tableName : mySign.TableAlias;//自定义表名
                }

                LogsHelper.addLog($"当前预操作--表名{tableName}\r\n");

                deleteTableSql = $"delete from {tableName} where 1=1";

                if (rows.Count > 0)
                {
                    //是否进行自定义处理
                    if (mySign != null && mySign.DefinedHander)
                    {
                        doCount = DefinedHander(tableName, dataColumns, rows, mySign, deleteTableSql, currentosZbSupplier, currentProject, doCount);
                        continue;
                    }

                    sqlHeadSbf = new StringBuilder();
                    contentSbf = new StringBuilder();

                    sqlHeadSbf.Append($"insert into {tableName}(");

                    //列循环
                    for (int k = 0; k < dataColumns.Count; k++)
                    {
                        // 1.字段匹配 2.不在过滤字段中
                        if (
                            mySign == null
                            || (mySign.Fields != null && mySign.Fields.ContainsKey(dataColumns[k].ColumnName))
                            || (mySign.Fields == null && !mySign.IgoreFields.ContainsKey(dataColumns[k].ColumnName))
                          )
                        {
                            sqlHeadSbf.Append($"{dataColumns[k].ColumnName},");
                            columsDict.Add($"{dataColumns[k].ColumnName}", "");
                            //
                            allColums.Append(dataColumns[k].ColumnName + ",");
                        }

                    }

                    //供应商基本信息加个字段 --投标项目编码
                    if ("OS_ZB_SUPPLIER_INFO".Equals(tableName))
                    {
                        sqlHeadSbf.Append($"BID_PROJECT_CODE,");
                        //供应商删除 根据id删除
                        deleteTableSql += columsDict.ContainsKey("ID") ? $" AND ID ='{currentosZbSupplier.Id}'  " : "";
                    }
                    else if ("OS_ZB_SUPPLIER_DEPOSIT_DETAIL".Equals(tableName))//供应商保证金详情
                    {
                        deleteTableSql += columsDict.ContainsKey("MARK_NO") ? $" AND MARK_NO in ({currentProject.Marks})  " : "";
                    }


                    sqlHeadSbf.Remove(sqlHeadSbf.Length - 1, 1);
                    sqlHeadSbf.Append(")");

                    contentSbf.Append($"{sqlHeadSbf}");

                    for (int k = 0; k < rows.Count; k++)
                    {
                        values = rows[k].ItemArray;
                        contentSbf.Append($" select ");

                        for (int rind = 0; rind < values.Length; rind++)
                        {

                            //跳过忽略字段
                            if (mySign != null &&
                                ((mySign.Fields != null && !mySign.Fields.ContainsKey(dataColumns[rind].ColumnName))
                                || mySign.IgoreFields.ContainsKey(dataColumns[rind].ColumnName))
                                )
                            {
                                continue;
                            }

                            currentValue = values[rind];

                            if (currentValue == null || string.IsNullOrWhiteSpace(currentValue.ToString()))
                            {
                                contentSbf.Append($"NULL,");
                            }
                            else if (mySign != null && mySign.FormatData.ContainsKey(dataColumns[rind].ColumnName))//是否存在格式字段
                            {
                                contentSbf.Append($"{string.Format(mySign.FormatData[dataColumns[rind].ColumnName], currentValue)},");
                            }
                            else
                            {
                                contentSbf.Append($"'{currentValue}',");
                            }
                        }

                        //供应商基本信息加个字段 --投标项目编码
                        if ("OS_ZB_SUPPLIER_INFO".Equals(tableName))
                        {
                            contentSbf.Append($"'{currentProject.ProjectNo}',");
                        }

                        contentSbf.Remove(contentSbf.Length - 1, 1);// 移除最后一个字符 “,”
                        contentSbf.Append(" from dual " + (k == rows.Count - 1 ? "" : " union all "));
                    }

                    //附加条件  ==> 排除一些
                    if (!"OS_ZB_MATERIAL_LIST".Equals(tableName))
                    {
                        deleteTableSql += columsDict.ContainsKey("PROJECT_NO") ? $" AND PROJECT_NO ='{currentProject.ProjectNo}'  " : "";
                    }

                    deleteTableSql += columsDict.ContainsKey("SUPPLIER_ID") ? $" AND SUPPLIER_ID ='{currentosZbSupplier.Id}'  " : "";


                    if ("OS_ZB_SUPPLIER_CREDIT_RELATE".Equals(tableName))
                    {
                        Console.WriteLine("-----");
                    }


                    if (!string.IsNullOrEmpty(deleteTableSql))
                    {
                        LogsHelper.addLog($"预执行删除sql语句---> {deleteTableSql} ");
                        int resultRow = OracleHelper.ExecuteSqlNoQuery(deleteTableSql, false);
                        if (resultRow < 0)
                        {
                            LogsHelper.AddErrorLog($"删除失败--表名{tableName}\r\n");
                        }
                    }

                    LogsHelper.addLog($"\r\n预执行插入sql语句条数:{rows.Count}条，当前操作列:{allColums.ToString()}");
                    LogsHelper.addLog($"\r\n预执行插入sql语句---> {contentSbf.ToString()} ");

                    int affectRow = OracleHelper.ExecuteSqlNoQuery(contentSbf.ToString(), false);

                    //操作失败写入数据库
                    if (affectRow < 0)
                    {
                        Console.WriteLine($"数据插入失败--表名{tableName}");
                        LogsHelper.AddErrorLog($"数据插入失败--表名{tableName}\r\n");
                        LogsHelper.AddErrorLog($"sql语句:{contentSbf}\r\n");
                        // LogsHelper.AddErrorLog($"数据插入失败--表名{tables[i].TableName},sql语句:{sqlContent}\r\n");
                    }
                    else
                    {
                        doCount++;
                        Console.WriteLine($"数据插入成功--表名{tableName}");
                        LogsHelper.addLog($"数据插入成功--表名{tableName}");
                    }

                }

            }

            LogsHelper.addLog($"数据操作完毕,操作表数量为:{doCount}");

        }


        /// <summary>
        /// 自定义处理 个别表数据
        /// </summary>
        /// <param name="tableName">当前操作表名</param>
        /// <param name="dataColumns"></param>
        /// <param name="rows"></param>
        /// <param name="mySign"></param>
        /// <param name="deleteTableSql"></param>
        /// <returns></returns>
        private int DefinedHander(string tableName, DataColumnCollection dataColumns, DataRowCollection dataRows, MySign mySign, string deleteTableSql, OsZbSupplierInfo currentosZbSupplier, OsZbPurchaseProjectInfo currentProject, int doCount)
        {
            StringBuilder insertSbf = new StringBuilder();
            StringBuilder deleteSbf = new StringBuilder();
            int affectRow = 0;
            byte[] fileBytes;
            string saveFilePath;
            FileInfo fileInfo;
            string parentDirectory;
            BinaryWriter bw = null;
            //项目信息=》 报名信息
            if ("OS_ZB_PURCHASE_PROJECT_INFO".Equals(tableName))
            {
                //删除
                deleteSbf.Append($"delete from OS_ZB_SUPPLIER_SIGN_UP where SUPPLIER_ID='{currentosZbSupplier.Id}' and SOURCE ='parse'");
                //插入
                insertSbf.Append("insert into OS_ZB_SUPPLIER_SIGN_UP(");
                insertSbf.Append("ID,PROJECT_NO,MARK_NO,PACK_NO,SUPPLIER_ID,SING_UP_TIME,CREATE_USER,CREATE_TIME");
                insertSbf.Append(",ENT_NAME,PACK_NAME,PROJECT_NAME,SOURCE,PROJECT_UNIT");
                insertSbf.Append(")");

                for (int i = 0; i < dataRows.Count; i++)
                {
                    //已选择 为已报名
                    if ("1".Equals(dataRows[i].Field<string>("SELECTED")))
                    {
                        insertSbf.Append($" select ");

                        insertSbf.Append($"'{Guid.NewGuid().ToString("N")}',");
                        insertSbf.Append($"'{dataRows[i].Field<string>("PROJECT_NO")}',");
                        insertSbf.Append($"'{dataRows[i].Field<string>("MARK_NO")}',");
                        insertSbf.Append($"'{dataRows[i].Field<string>("PACK_NO")}',");// PARK_NO没有这个字段
                        insertSbf.Append($"'{currentosZbSupplier.Id}',");
                        insertSbf.Append($"to_timestamp('{dataRows[i].Field<string>("CREATE_TIME")}','yyyy-mm-dd hh24:mi:ss'),");
                        insertSbf.Append($"'{currentosZbSupplier.Id}',");
                        insertSbf.Append($"systimestamp,");
                        insertSbf.Append($"'{currentosZbSupplier.EntName}',");
                        insertSbf.Append($"'{dataRows[i].Field<string>("PACK_NAME")}',");
                        insertSbf.Append($"'{dataRows[i].Field<string>("PROJECT_NAME")}',");
                        insertSbf.Append($"'parse',");//来源写死
                        insertSbf.Append($"NULL");//此字段没有

                        insertSbf.Append(" from dual union all");
                    }
                }

                insertSbf.Remove(insertSbf.Length - "union all".Length - 1, "union all".Length + 1);//删除最后一个union all

            }
            //文件信息 =》 线上文件信息 ==>CM_C_ENCLOSURE_FILE
            else if ("SYS_FILE_INFO".Equals(tableName))
            {
                //删除
                deleteSbf.Append($"delete from CM_C_ENCLOSURE_FILE where NOTE='{currentosZbSupplier.Id + "-" + currentProject.ProjectNo}'");
                insertSbf.Append("INSERT INTO CM_C_ENCLOSURE_FILE(");
                insertSbf.Append(" ENCLOSURE_ID,ENCLOSURE_SUB_CODE,FILE_PATH,FILE_FORMAT,UPLOAD_TIME");
                insertSbf.Append(",FILE_DISP_NAME,CREATE_USER,CREATE_TIME,IS_DELETE,RVRS_STR1,RVRS_STR2,FILE_SIZE");
                insertSbf.Append(",NOTE");
                insertSbf.Append(")");
                string file_format;
                string realFilePath;
                string[] fileArr;
                string fileName;
                string filekey;

                for (int i = 0; i < dataRows.Count; i++)
                {
                    file_format = dataRows[i].Field<string>("FILE_FORMAT");
                    file_format = file_format != null ? file_format.Remove(0, 1) : file_format;
                    //默认根路径
                    realFilePath = dataRows[i].Field<string>("FILE_PATH");//默认路径
                    filekey = dataRows[i].Field<string>("RELATED_KEY");//文件key值

                    // 标书上传
                    if ("OS_ZB_SUPPLIER_BID_ATTACHMENT".Equals(dataRows[i].Field<string>("RELATED_PAGE")))
                    {
                        fileName = dataRows[i].Field<string>("FILE_DISP_NAME");
                        dataRows[i].Field<string>("RELATED_KEY");
                        fileName = fileName.Replace("商务投标支持文件", "").Replace("技术投标支持文件", "").Replace("附件", "");
                        fileName = fileName.Replace(".pdf", "").Replace(".zip", "");
                        //剩下是从项目-到包
                        fileArr = fileName.Split('_');
                        realFilePath = "";

                        for (int ind = 0; ind < fileArr.Length; ind++)
                        {
                            //项目编码-项目名称 /供应商名称/ 标段/包号 /{商务支持文件/技术支持文件}/
                            if (ind == 0)
                            {
                                realFilePath += $"{fileArr[0]}-{currentProject.ProjectName}\\{currentosZbSupplier.EntName}";
                            }
                            else if (ind == 1)//标
                            {
                                realFilePath += $"\\{fileArr[1]}";
                            }
                            else if (ind == 2)
                            {
                                realFilePath += $"\\{fileArr[2]}";
                            }
                        }

                        //商务文件还是技术文件
                        realFilePath += filekey == "SWZCWJ" ? "\\商务支持文件\\" : "\\技术支持文件\\";
                        realFilePath += dataRows[i].Field<string>("FILE_DISP_NAME");//文件名称
                    }
                    else// 大部分情况
                    {
                        realFilePath = $"{currentProject.ProjectNo}-{currentProject.ProjectName}\\{dataRows[i].Field<string>("FILE_PATH")}";//默认路径
                    }


                    insertSbf.Append($" select ");
                    insertSbf.Append($"'{dataRows[i].Field<string>("ID")}',");
                    insertSbf.Append($"'1',");
                    //insertSbf.Append($"'{dataRows[i].Field<string>("FILE_PATH")}',");
                    insertSbf.Append($"'{realFilePath}',");
                    insertSbf.Append($"'{file_format}',");
                    insertSbf.Append($"to_timestamp('{dataRows[i].Field<string>("UPLOAD_TIME")}','yyyy-mm-dd hh24:mi:ss'),");//UPLOAD_TIME
                    insertSbf.Append($"'{dataRows[i].Field<string>("FILE_DISP_NAME")}',");
                    insertSbf.Append($"'{currentosZbSupplier.EntName}',");//供应商名称
                    insertSbf.Append($"to_timestamp('{dataRows[i].Field<string>("UPLOAD_TIME")}','yyyy-mm-dd hh24:mi:ss'),");
                    insertSbf.Append($"'1',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("RELATED_ID")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("RELATED_KEY")}',");
                    insertSbf.Append($"'{dataRows[i].Field<Int64>("SIZE")}',");
                    insertSbf.Append($"'{currentosZbSupplier.Id + "-" + currentProject.ProjectNo}'");
                    insertSbf.Append(" from dual " + (i == dataRows.Count - 1 ? "" : " union all "));


                    //将二进制流文件 写到相对路径里面
                    fileBytes = dataRows[i].Field<byte[]>("BINARY_FILE");

                    if (fileBytes != null)
                    {
                        try
                        {
                            //存储路径
                            saveFilePath = Path.Combine(saveFileRootPath, realFilePath);
                            fileInfo = new FileInfo(saveFilePath);
                            parentDirectory = fileInfo.Directory.FullName;
                            if (!Directory.Exists(parentDirectory))
                            {
                                Directory.CreateDirectory(parentDirectory);
                            }
                            bw = new BinaryWriter(File.Open(saveFilePath, FileMode.OpenOrCreate));
                            bw.Write(fileBytes);
                        }
                        catch (Exception ex)
                        {
                            LogsHelper.AddErrorLog($"文件写入异常:{ex.Message}");
                        }
                        finally
                        {
                            if (bw != null)
                            {
                                bw.Close();
                            }
                        }

                    }

                }
            }

            //标书上传信息
            else if ("OS_ZB_SUPPLIER_BID_ATTACHMENT".Equals(tableName))
            {
                //删除
                deleteSbf.Append($"delete from OS_ZB_SUPPLIER_BID_ATTACHMENT where SUPPLIER_ID='{currentosZbSupplier.Id}' and PROJECT_NO ='{currentProject.ProjectNo}'");

                insertSbf.Append("INSERT INTO OS_ZB_SUPPLIER_BID_ATTACHMENT(");
                insertSbf.Append(" ID,BID_ID,SUPPLIER_ID,PROJECT_NO,MARK_NO,PACK_NAME,PACK_NO");
                insertSbf.Append(",ATTACH_ID,IS_DELETE,REMARK,CREATE_USER,CREATE_TIME,UPDATE_USER,UPDATE_TIME");
                insertSbf.Append(",IS_DECRYPT,DECRYPT_TIME,DECRYPT_USER,DECRYPT_STATUS,SIGN_KEY,ATTACH_TYPE,FAIL_REASON");
                insertSbf.Append(",ARCHIVE_STATUS,ARCHIVE_KEY,ZIP_ATTACH_ID,ZIP_ARCHIVE_KEY");
                insertSbf.Append(")");


                for (int i = 0; i < dataRows.Count; i++)
                {
                    insertSbf.Append($" select ");
                    insertSbf.Append($"'{dataRows[i].Field<string>("ID")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("BID_ID")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("SUPPLIER_ID")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("PROJECT_NO")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("MARK_NO")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("PACK_NAME")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("PACK_NO")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("ATTACH_ID")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("IS_DELETE")}',");
                    insertSbf.Append($"'{dataRows[i].Field<string>("REMARK")}',");
                    insertSbf.Append($"'{currentosZbSupplier.EntName}',");
                    insertSbf.Append($"to_timestamp('{dataRows[i].Field<string>("CREATE_TIME")}','yyyy-mm-dd hh24:mi:ss'),");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"'1',");
                    insertSbf.Append($"'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}',");//解密时间
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"'SUCCESS',");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append("'" + ("skill".Equals(dataRows[i].Field<string>("FILE_TYPE")) ? "JSZCWJ" : "SWZCWJ") + "',");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"NULL,");
                    insertSbf.Append($"'{dataRows[i].Field<string>("ZIP_ATTACH_ID")}',");//压缩文件字段
                    insertSbf.Append($"NULL");//压缩文件字段
                    insertSbf.Append(" from dual " + (i == dataRows.Count - 1 ? "" : " union all "));

                }
            }


            if (deleteSbf.Length > 6)
            {
                affectRow = OracleHelper.ExecuteSqlNoQuery(deleteSbf.ToString(), false);
            }
            if (insertSbf.Length > 6)
            {
                affectRow = OracleHelper.ExecuteSqlNoQuery(insertSbf.ToString(), false);
            }




            //操作失败写入数据库
            if (affectRow < 0)
            {
                Console.WriteLine($"数据插入失败--表名{tableName}");
                LogsHelper.AddErrorLog($"数据插入失败--表名{tableName}\r\n");
            }
            else
            {
                doCount++;
                Console.WriteLine($"数据插入成功--表名{tableName}");
                LogsHelper.addLog($"数据插入成功--表名{tableName}");
            }

            return doCount;
        }

        //文件和文件解析状态
        private void AppendListViewItemToLogs(string filePath, string status)
        {
            if (File.Exists(filePath))
            {
                string fileName = Path.GetFileName(filePath);

                string curTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                ListViewItem listView = new ListViewItem() { Text = curTime };
                listView.SubItems.Add(fileName);//第二列
                listView.SubItems.Add(status);//第三列
                listViewLogs.Items.Add(listView);
                listViewLogs.Refresh();

                LogsHelper.addLog($"解析文件:{filePath},解析状态:{status}");
            }
        }

        /// <summary>
        /// 暂时不用
        /// </summary>
        /// <param name="filePath"></param>
        private void AppendListViewItem(string filePath)

        {
            if (File.Exists(filePath))
            {
                string fileName = Path.GetFileName(filePath);
                ListViewItem listView = new ListViewItem() { Text = fileName };
                listViewFiles.Items.Add(listView);
                listViewFiles.Refresh();
            }
        }


        /// <summary>
        ///  删除待解析列表的该文件
        /// </summary>
        /// <param name="v"></param>
        private void RemoveListViewItem(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    //string fileName = Path.GetFileName(filePath);
                    ListView.ListViewItemCollection collection = listViewFiles.Items;
                    for (int i = 0; i < collection.Count; i++)
                    {
                        if (collection[i].Text == filePath)
                        {
                            listViewFiles.Items.RemoveAt(i);
                            listDict.Remove(filePath);
                        }
                    }

                    listViewFiles.Refresh();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }


        /// <summary>
        /// 任务开始
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonStart_Click(object sender, EventArgs e)
        {
            if (listViewFiles.Items.Count <= 0)
            {
                MessageBox.Show("没有需要解析的文件", "确定");
                this.lblunanalysedQty.Text = "0";
                return;
            }
            this.TimerParse.Start();
            this.buttonStart.ForeColor = System.Drawing.Color.Red;
            this.buttonStart.Text = "停止解析";
            this.buttonStart.Click -= ButtonStart_Click;
            this.buttonStart.Click += ButtonStop_Click;

            this.lblTimerMsg.Text = "解析任务进行中...";
            this.lblTimerMsg.ForeColor = System.Drawing.Color.Red;
            this.DbPathSelect.Enabled = false;
            this.FilePathSelect.Enabled = false;
            //this.rootPathSelect.Enabled = false;
        }

        /// <summary>
        /// 停止解析
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ButtonStop_Click(object sender, EventArgs e)
        {
            StopParse("已停止解析...");
        }


        /// <summary>
        /// 解析任务 执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TimerParse_Tick(object sender, EventArgs e)
        {
            try
            {
                //有数据正在解析 不进行重复解析 也防止列表数据重复
                if (!IS_PARSING)
                {
                    //ParseDB();
                    Thread curThread = new Thread(new ThreadStart(ParseDB));
                    curThread.Start();
                }
            }
            catch (Exception ex)
            {
                LogsHelper.AddErrorLog("解析错误:" + ex.Message);
            }
        }


        /// <summary>
        /// 获取读取文件根路径
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void rootPathSelect_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                if ("DB".Equals(((Button)sender).Tag.ToString()))
                {
                    this.DbPathText.Text = dialog.SelectedPath;
                    this.DbPathText.Update();
                    GetDBList();
                }
                else if ("FileSave".Equals(((Button)sender).Tag.ToString()))
                {
                    this.rootPathText.Text = dialog.SelectedPath;
                    this.rootPathText.Update();
                    this.saveFileRootPath = dialog.SelectedPath;
                }

            }
        }

        /// <summary>
        /// 日志清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogBtn_Click(object sender, EventArgs e)
        {
            this.listViewLogs.Items.Clear();
        }


        /// <summary>
        /// 刷新按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshDBList_Click(object sender, EventArgs e)
        {
            GetDBList();
        }


        /// <summary>
        /// 复制粘贴功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ListView_MouseDown(object sender, MouseEventArgs e)
        {
            //鼠标右键
            if (e.Button == MouseButtons.Right && sender is ListView && ((ListView)sender).Items.Count > 0)
            {
                ListView curListView = sender as ListView;
                this.CopyItem.Tag = curListView;//当前操作的listView
                this.RemoveItem.Visible = !IS_PARSING && "listViewFiles".EndsWith(curListView.Name);
                MouseMenu.Show(MousePosition.X, MousePosition.Y);
            }

        }

        /// <summary>
        /// 点击了复制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MouseMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            try
            {
                if (e.ClickedItem is ToolStripItem && "CopyItem".Equals(((ToolStripItem)e.ClickedItem).Name))
                {
                    ListView curListView = this.CopyItem.Tag as ListView;
                    ListView.SelectedListViewItemCollection selectedItems = curListView.SelectedItems;

                    ListView.ColumnHeaderCollection columns = curListView.Columns;

                    StringBuilder sbf = new StringBuilder();
                    ListViewItem viewItem;
                    ListViewItem.ListViewSubItemCollection subItem;
                    for (int i = 0; i < selectedItems.Count; i++)
                    {
                        viewItem = selectedItems[i];
                        subItem = viewItem.SubItems;
                        for (int j = 0; j < subItem.Count; j++)
                        {
                            sbf.Append($" {subItem[j].Text} ");
                        }
                        sbf.Append(" \r\n ");
                    }
                    Clipboard.SetDataObject(sbf.ToString());
                }
                else if (e.ClickedItem is ToolStripItem && "RemoveItem".Equals(((ToolStripItem)e.ClickedItem).Name) && !IS_PARSING)
                {
                    ListView curListView = this.CopyItem.Tag as ListView;
                    ListView.SelectedListViewItemCollection selectedItems = curListView.SelectedItems;
                    for (int i = 0; i < selectedItems.Count; i++)
                    {
                        listDict.Remove(selectedItems[i].Text);
                        this.initParseCount--;
                        curListView.Items.Remove(selectedItems[i]);
                    }
                    this.lblunanalysedQty.Text = Convert.ToString(this.initParseCount);
                }
            }
            catch (Exception ex)
            {
                LogsHelper.AddErrorLog($"复制到剪切板异常:{ex.Message}");
            }
        }

        private void listViewLogs_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        /// <summary>
        /// 解析日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LogBtn_Click(object sender, EventArgs e)
        {
            ParseLogFrm frm = new ParseLogFrm();
            frm.StartPosition = FormStartPosition.CenterParent;
            frm.ShowDialog();
        }

        /// <summary>
        /// 退出应用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ParseForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
        }

        private void listViewFiles_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 刷新配置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RefreshConfig_Click(object sender, EventArgs e)
        {
            fiterTables = GetTableConfig();
        }
    }


}
